package com.demo.common.interceptor;

import com.demo.common.permission.login.RequestService;
import com.demo.common.permission.login.TokenInfo;
import com.demo.common.utils.JsonUtil;
import com.demo.common.vo.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * token拦截器（登录拦截器）
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private RequestService requestService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception{
        response.setContentType("application/json");
        response.setCharacterEncoding(String.valueOf(StandardCharsets.UTF_8));
        String errorMsg = requestService.checkToken();
        if(errorMsg!=null){
            //校验失败直接返回信息
            Result result=Result.error(errorMsg);
            response.getWriter().write(JsonUtil.object2Json(result));
            return false;
        }
        TokenInfo tokenInfo = requestService.getTokenInfo();
        //刷新token
        if(LocalDateTime.now().isAfter(tokenInfo.getFlushTime())){
            tokenInfo.setFlushTime(LocalDateTime.now().plusHours(18));
            requestService.setTokenInfo(tokenInfo);
        }
        return true;
    }

}
